/*
 * @Author: tangyuhui 317972442@qq.com
 * @Date: 2024-08-27 00:58:30
 * @LastEditors: tangyuhui 317972442@qq.com
 * @LastEditTime: 2024-09-27 18:05:42
 */
import { Task } from './types';
import dayjs from 'dayjs'
import {EmployeeWorkRecord,EmployeeObject,ICompletionStatus} from './types'
import {statuses,finishedStatuses} from './enum'
import html2canvas from "html2canvas";
/*
 * @description: 计算工作饱和度
 * @author: tangyuhui
 * @date: 2024-08-27 22:15:18
*/



export function calcWorkloadSaturation(data:Record<string, any>): EmployeeWorkRecord {
  const tasks: EmployeeWorkRecord = {}; // 初始化为空对象，符合 EmployeeWorkRecord 类型

  const processLeaders = (leaders: string, laborHour: string, item: Task) => {
    if (isNotYunXiaoNull(leaders)) {
      leaders.split(',').forEach(leader => {
        leader = leader.trim(); // 去除可能的空格
        if (leader) {
          updateEmployeeTasks(tasks, leader, laborHour, item);
        }
      });
    }
  };
  data && data.forEach((item:Task) => {
    // 处理 frontEndLeader
    if (isNotYunXiaoNull(item.frontEndLeader)) {
      processLeaders(item.frontEndLeader, item.frontLaborHour, item);
    }

    // 处理 backEndLeader
    if (isNotYunXiaoNull(item.backEndLeader)) {
      processLeaders(item.backEndLeader, item.backendLaborHour, item);
    }

    // 处理 testLeader
    if (isNotYunXiaoNull(item.testLeader)) {
      processLeaders(item.testLeader, item.testLaborHour, item);
    }
  });

  console.log(tasks);
  return tasks;
} 

/*
 * @description: 更新记录
 * @author: tangyuhui
 * @date: 2024-08-27 22:15:28
*/
function updateEmployeeTasks(
  tasks: EmployeeWorkRecord,
  leader: string,
  hours: string,
  item: Task
) {
  const hoursNum = isNotYunXiaoNull(hours) ? parseFloat(hours) : 0;
  if (!tasks[leader]) {
    tasks[leader] = { workHour: 0, taskList: []};
  }
  // 去重先 
  if(!tasks[leader].taskList.find(taskobj=>taskobj.task===item.task)){
    tasks[leader].taskList.push(item);
  }
  tasks[leader].workHour += hoursNum;
}

export function isNotYunXiaoNull(data:any){
  return data !== '--' && data!==undefined && data!==null
}


// 预计本周提测任务
export function findTasksToTestThisWeek(tasks:Task[]) {
  return tasks && tasks.filter((task) => {
    const testingDate = parseDate(task.testingTime);
    return testingDate && isThisWeek(testingDate) && !finishedStatuses.includes(task.status);
  });
}

// 预计今天提测任务
export function findTasksToTestToday(tasks:Task[]) {
  return tasks && tasks.filter((task) => {
    const testingDate = parseDate(task.testingTime);
    return testingDate && isToday(testingDate) && !finishedStatuses.includes(task.status);
  });
}

// 预计今天上线内容
export function findTasksToDeployToday(tasks:Task[]) {
  return tasks && tasks.filter((task) => {
    const deploymentDate = parseDate(task.onlineTime);
    return deploymentDate && isToday(deploymentDate);
  });
}

//预计本周上线内容
export function findTasksToDeployWeek(tasks:Task[]) {
  return tasks && tasks.filter((task) => {
    const deploymentDate = parseDate(task.onlineTime);
    return deploymentDate && isThisWeek(deploymentDate);
  });
}


// 找到已经超出提测时间，但状态不是 测试中、测试完成、待验收、待发布、已关闭 的任务
export function findTasksExceedingTestingTime(tasks:Task[]) {
  const invalidStatuses = [
    "测试中",
    "测试完成",
    "待验收",
    "待发布",
    "已发布",
    "已完成",
    "已关闭",
  ];

  return tasks && tasks.filter((task) => {
    const testingDate = parseDate(task.testingTime);
    return isPastDate(testingDate) && !invalidStatuses.includes(task.status);
  });
}

// 找到已经超出上线时间，但状态不是 已发布、已关闭的任务
export function findTasksExceedingDeploymentTime(tasks:Task[]) {
  return tasks&&tasks.filter((task) => {
   return exceedDeployTime(task)
  });
}

// 超出上线时间
export function exceedDeployTime(task:Task){
  const deploymentDate = parseDate(task.onlineTime);
   return isPastDate(deploymentDate) && !finishedStatuses.includes(task.status);
}

// 超出提测时间
export function exceedTestTime(task:Task){
  const invalidStatuses = [
    "测试中",
    "测试完成",
    "待验收",
    "待发布",
    "已发布",
    "已完成",
    "已关闭",
  ];
  const testingDate = parseDate(task.testingTime);
  return isPastDate(testingDate) && !invalidStatuses.includes(task.status);
}

// Function to check if a date is in the past
export function isPastDate(date:Date) {
    const today = new Date();
    today.setHours(0, 0, 0, 0); // Normalize today's date to 00:00:00 for comparison
    return date < today;
  }
// Utility function to parse date strings
export function parseDate(dateString:string) {
  return new Date(dateString);
}

 
  // Function to check if a date is today
  function isToday(date:Date) {
    const today = new Date();
    return date.toDateString() === today.toDateString();
  }
 
// Function to check if a date is within the current week (Monday to Sunday)
function isThisWeek(date:Date) {
  const today = new Date();
  const dayOfWeek = today.getDay(); // Sunday - Saturday : 0 - 6
  const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek; // If today is Sunday, offset to last Monday
  const sundayOffset = dayOfWeek === 0 ? 0 : 7 - dayOfWeek; // If today is Sunday, Sunday is today

  const firstDayOfWeek = new Date(today);
  firstDayOfWeek.setDate(today.getDate() + mondayOffset);
  firstDayOfWeek.setHours(0, 0, 0, 0);

  const lastDayOfWeek = new Date(today);
  lastDayOfWeek.setDate(today.getDate() + sundayOffset);
  lastDayOfWeek.setHours(23, 59, 59, 999);

  return date >= firstDayOfWeek && date <= lastDayOfWeek;
}

export function sortItemsByTime(a:Task, b:Task,field:string){
    if (!isNotYunXiaoNull(a[field])) return 1; // 如果 a 是 '--'，则 a 应该排在 b 后面
    if (!isNotYunXiaoNull(b[field])) return -1; // 如果 b 是 '--'，则 b 应该排在 a 后面

    const timeA = dayjs(a[field] as string);
    const timeB = dayjs(b[field] as string);

    return timeA.isBefore(timeB) ? -1 : timeA.isAfter(timeB) ? 1 : 0;
}


/*
 * @description:判断任务是否已经开发完成
 * @author: tangyuhui
 * @date: 2024-08-27 22:54:13
*/
export function isAfterDevelopment(item:Task,record:EmployeeObject) {
  // 当前定义的人是：
  const name = record.name
  // 找到当前任务是 前端、后端、测试
  const roles = {
    [item.frontEndLeader]: '前端负责人',
    [item.backEndLeader]: '后端负责人',
    [item.testLeader]: '测试负责人'
  };
  // 定义状态顺序
  let finishIndex= 0
  if (roles[name]==='前端负责人'|| roles[name]==='后端负责人') {
    // 获取 "开发中" 的索引
    finishIndex = statuses.indexOf('开发中');
  }else{
      // 获取 “测试中” 的索引
    finishIndex = statuses.indexOf('测试中');
  }
  // 获取传入状态的索引
  const statusIndex = statuses.indexOf(item.status);

  // 如果状态不在列表中，返回 false
  if (statusIndex === -1) {
    return false;
  }

  // 判断状态是否在 "开发中" 之后
  return statusIndex > finishIndex;
}

 
/*
 * @description: 找到没有估时的任务
 * @author: tangyuhui
 * @date: 2024-08-28 16:02:42
*/

export function findTasksNotPredictedTime(tasks: Task[]) {
  if (!tasks || tasks.length === 0) {
    return { noFront: [], noBackend: [], noTest: [] ,noDevelop:[],noTestFinishTime:[],noPublishTime:[],notFinished:[]};
  }

  // 获取 “测试中” 的索引
  const finishTestIndex = statuses.indexOf('测试中');
  
  // 初始化结果对象
  const result = {
    noFront: [] as Task[],
    noBackend: [] as Task[],
    noTest: [] as Task[],
    noDevelop:[] as Task[],
    noTestFinishTime:[] as Task[], // 没有测试完成时间
    noPublishTime:[] as Task[], // 没有发布时间
    notFinished:[] as Task[]
  };

  // 遍历任务数组一次
  tasks.forEach((task) => {
    // 获取传入状态的索引
    const statusIndex = statuses.indexOf(task.status);
    const isFinish = statusIndex >= finishTestIndex;

    // 根据条件将任务分类
    if (!isFinish) {
      if (!isNotYunXiaoNull(task.frontLaborHour) && !isNotYunXiaoNull(task.testingTime) && isNotYunXiaoNull(task.frontEndLeader)) {
        result.noFront.push(task);
      }
      if (!isNotYunXiaoNull(task.backendLaborHour) && !isNotYunXiaoNull(task.testingTime) && isNotYunXiaoNull(task.backEndLeader)) {
        result.noBackend.push(task);
      }
    }
    if (!isNotYunXiaoNull(task.testLaborHour) && !isNotYunXiaoNull(task.finishTestingTime)&& !finishedStatuses.includes(task.status) && isNotYunXiaoNull(task.testLeader)) {
        result.noTest.push(task);
    }
    // 没有测试完成时间
    if (!isNotYunXiaoNull(task.finishTestingTime)&& !finishedStatuses.includes(task.status) && isNotYunXiaoNull(task.testLeader)) {
      result.noTestFinishTime.push(task);
    }
    if (!isNotYunXiaoNull(task.planOnlineTime)&& !finishedStatuses.includes(task.status)) {
      result.noPublishTime.push(task);
    }
    // 前端空 后端空
    if (!isNotYunXiaoNull(task.frontEndLeader) && !isNotYunXiaoNull(task.backEndLeader)) {
      result.noDevelop.push(task);
     }
      // 前端空 后端空
    if (!finishedStatuses.includes(task.status)) {
      result.notFinished.push(task);
     }
  })
  return result
}


 /*
  * @description: 计算工时
  * @author: tangyuhui
  * @date: 2024-08-30 09:31:57
 */
export function convertWorkSaturation(
  elementsData: Record<string, any>
) {
  const data:EmployeeWorkRecord = calcWorkloadSaturation(elementsData);
  if (data) {
    const convertData = Object.entries(data).map(([key, value]) => {
      return { name: key, workHours: value.workHour, taskList: value.taskList };
    });
    return convertData;
  } else {
    return [];
  }
}

// 截图
export const capturePage =  async (dom:HTMLElement) => {
  if (dom) {
    const element =dom;
    // 使用 html2canvas 对引用的元素进行截图
    const canvas = await html2canvas(element, {
      width: element.scrollWidth,
      height: element.scrollHeight,
    });
    // 将 canvas 转换为图片 URL
    const dataUrl = canvas.toDataURL("image/png");
    // 也可以将截图下载为图片
    canvas.toBlob((blob) => {
      if (blob) {
        // 如果 blob 不为 null，则执行以下操作
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "screenshot.png";
        a.click();
        URL.revokeObjectURL(url);
      } else {
        console.error("Failed to create Blob from canvas.");
      }
    });
  }
}

/*
 * @description:计算工时完成率
 * @author: tangyuhui
 * @date: 2024-09-11 13:35:30
*/
export const calCompletion= (tasks:Task[]):ICompletionStatus=>{
  const total = tasks.length
  if (total === 0) {
    return {
      finishTask: [], // 完成的任务
      completion: 0,
    }
  }
  const finishTask = tasks.filter((task) => {
    return finishedStatuses.includes(task.status);
  })
  // 计算完成率
  return {
    finishTask: finishTask, // 完成的任务
    completion: Math.round((finishTask.length / total) * 100),
  };
}